package com.fw.application.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.BaseController;
import com.fw.common.IdXD;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.FwUcjoin;
import com.fw.system.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static com.fw.mes.ResultUtils.success;


/**
 * <p>
 * 我的收藏中间表 前端控制器
 * </p>
 *
 * @since 2021-05-10
 */
@RestController
@RequestMapping("/ucjoin")
@RequiredArgsConstructor
@Api(tags = "收藏")
public class FwUcjoinController implements BaseController {

    @Autowired
    private IFwUcjoinService ucjoinService;
    @Autowired
    private IFwSpuService spuService;
    @Autowired
    private IdXD idXD;

    @ApiOperation("我的收藏列表")
    @GetMapping("/list")
    public Result<List<FwUcjoin>> list(){
        List<FwUcjoin> ucjoinList = ucjoinService.list(Wrappers.<FwUcjoin>lambdaQuery()
                .eq(FwUcjoin::getUserId, getUser().getId()));
        ucjoinList.forEach(uc-> uc.setFwSpu(spuService.getById(uc.getItemId())));
        return success(ucjoinList);
    }

    @ApiOperation("收藏/取消")
    @GetMapping("/keep/{spuId}")
    public Result<Object> keep(@PathVariable String spuId){
        FwUcjoin ucjoin = ucjoinService.getOne(Wrappers.<FwUcjoin>lambdaQuery()
                .eq(FwUcjoin::getUserId, getUser().getId())
                .eq(FwUcjoin::getItemId, spuId));
        if (ucjoin != null){
            ucjoinService.removeById(ucjoin);
            return success("取消收藏");
        }
        ucjoinService.save(new FwUcjoin()
                .setCreateTime(LocalDateTime.now())
                .setItemId(spuId)
                .setUpdateTime(LocalDateTime.now())
                .setUserId(getUser().getId())
                .setId(idXD.nextId()));
        return success("添加收藏");
    }
}

